import axios from "../utils/axios"
import apis from "../apis"
//const toTree = (data)=>{
//	var rs = {};
//	for(let i=0;i<data.length;i++){
//		var permission = data[i];
//		if(permission.parentid==0){
//			permission.children =[];
//			rs[permission._id]=permission;
//		}
//	}
//	for(let i=0;i<data.length;i++){
//		var permission=data[i];
//		for(var key in rs){
//			if(permission.parentid==key){
//				rs[key].children.push(permission)
//			}
//		}
//	}
//	return rs;
//}

var toTree = (data)=> {
    // 删除 所有 children,以防止多次调用
    data.forEach(function (item) {
        delete item.children;
    });
    // 将数据存储为 以 id 为 KEY 的 map 索引数据列
    var map = {};
    data.forEach(function (item) {
        item.label = item.permissionDesc;
        map[item._id] = item;
    });
    var val = [];
    data.forEach(function (item) {
        // 以当前遍历项，的pid,去map对象中找到索引的id
        var parent = map[item.parentid];
        // 好绕啊，如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
        if (parent) {
            (parent.children || ( parent.children = [] )).push(item);
        } else {
            //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
            val.push(item);
        }
    });
    return val;
}


const state={
	allMenus:[],
	allPermissions:[],
	allroles:[],
	allusers:[],
	allgames:[]
}
const getters={
	allMenus(state){
		return toTree(state.allMenus);
	},
	allPermissions(state){
		return toTree(state.allPermissions);
	},
	allroles(state){
		return state.allroles;
	},
	allusers(state){
		return state.allusers;
	},
	allgames(state){
		return state.allgames;
	}
}
const mutations={
	LOADALLMENUS(state,payload){
		state.allMenus=payload;
	},
	LOADALLPERMISSIONS(state,payload){
		state.allPermissions=payload;
	},
	LOADALLROLES(state,payload){
		state.allroles=payload;
	},
	LOADALLZHANGHAO(state,payload){
		state.allusers=payload;
	},
	LOADALLGAMES(state,payload){
		state.allgames=payload;
	}
	
}
const actions={
	loadAllPermission({commit},payload){
		axios.get(apis.findAllPermission)
		.then((resp)=>{
			
			commit("LOADALLPERMISSIONS",resp.data.allPermission)
		})
	},
	loadallroles({commit},payload){
		axios.get(apis.juesexinxi)
		.then((resp)=>{
			
			commit("LOADALLROLES",resp.data.allRoles)
		})
	},
	loadallusers({commit},payload){
		axios.get(apis.zhanghuxinxi)
		.then((resp)=>{
			console.log(resp);
			commit("LOADALLZHANGHAO",resp.data.allUsers)
		})
	},
	loadallgames({commit},payload){
		axios.get(apis.findallgames)
		.then((resp)=>{
			console.log(resp);
			commit("LOADALLGAMES",resp.data.data[0].games)
		})
	}
	
}
export default{
	state,
	getters,
	mutations,
	actions
}
